<template>
  <view>
    <view class="demos-header">
      <h1 class="demos-title">
        <view class="logo">
          <u--image class="img" :src="src" mode="widthFix" @click="click" :fade="false" width="250px">
          </u--image>
        </view>
      </h1>
    </view>
    <view class="bg-bar"></view>

    <view class="content">
      <view class="weui-cells title-bar">
        <uni-icons type="sound" size="22" color="#d51717"></uni-icons>

        <span class="tip">懂你，是熊猫用心服务的第一步，期待你的回复，帮助熊猫实现爱的传递</span>
      </view>
      <view>
        <u--form labelPosition="left" :model="formData" labelWidth="250rpx">
          <view class="weui-cells">
            <u-form-item label="地区:" prop="address" borderBottom>
              <input v-model="formData.address" border="none" class="weui-input input-disabled" placeholder="请输入地区"
                disabled />
            </u-form-item>
            <view v-for="item in formItems" :class="{'error-status': !item.valid}">
              <u-form-item :label="item.label" borderBottom :required="item.required">
                <picker mode="selector" :value="item.selected" :range="item.dataList" class="picker"
                  @change="onChange($event,item)">
                  <view class="form-item">
                    <view class="c-333" v-if="item.dataList[item.selected]">{{item.dataList[item.selected]}}</view>
                    <view v-else class="c-999">请选择</view>
                    <uni-icons type="bottom" size="22"></uni-icons>
                  </view>
                </picker>
              </u-form-item>
              <view v-if="item.dataList[item.selected] === '其他'">
                <u-form-item label="其他:" borderBottom>
                  <u--input v-model="item.other" border="none" class="weui-input" :placeholder="item.otherPlacholder">
                  </u--input>
                </u-form-item>
              </view>
            </view>
            
            <template v-if="pagetype === '1'">
              <u-form-item label="您的下单手机号是:" prop="phoneNumber" :required="true" borderBottom :class="{'error-status': !formValid.phoneNumberValid}">
                <input v-model="formData.phoneNumber" border="none" class="weui-input" placeholder="请输入手机号码"/>
              </u-form-item>
              <u-form-item label="蛋糕配送日期是:" prop="time" :required="true" borderBottom :class="{'error-status': !formValid.dateValid}">
                <view class="form-item picker"  @click="showTimeSelect">
                  <view v-if="formData.date" class="c-333">
                    <view>{{formData.date}}</view>
                    <view>{{formData.time}}</view>
                  </view>
                  <view v-else class="c-999">请选择</view>
                  <uni-icons type="bottom" size="22"></uni-icons>
                </view>
              </u-form-item>
            </template>

            <view style="color: #d51717; padding: 5px 0px 30px 20px; font-size: 14px; ">带 * 为必填项目，请完成填写</view>
          </view>

          <view class="bottom">
            <button type="warn" @click="submitInfo">提交</button>
          </view>
        </u--form>
      </view>
    </view>
    
    <timeSelector ref="timeSelectorRef" @confirm="onDateConfirm"></timeSelector>
  </view>
</template>

<script>
  import utils from "@/libs/utils/utils.js"
  import {
    wechatAuth
  } from "@/libs/utils/wechat.js"
  import QQMapWX from '@/libs/qqmap.js'
  import timeSelector from '@/components/timeSelector.vue'
  import {
    feedbackSave
  } from '@/api/index.js'
  export default {
    data() {
      const pagetype = this.$route.query.pagetype
      return {
        pagetype: pagetype,
        qqMap: new QQMapWX({
          key: 'FTIBZ-H6SCX-SHK4F-7XM5U-TUVW7-YVFB4',
          vm: this
        }),
        src: "../../static/title_img.png",
        formItems: [{
          id: '1',
          required: true,
          selected: '',
          dataList: ['孩子', '父母', '爱人', '朋友', '其他'],
          label: '您希望将惊喜送给:',
          other: '',
          otherPlacholder: '请输入送给谁',
          valid: true
        }, {
          id: '2',
          required: true,
          selected: '',
          dataList: ['男性', '女性'],
          label: '即将收到惊喜的TA是:',
          valid: true
        }, {
          id: '3',
          required: true,
          selected: '',
          dataList: ['轻松热闹', '温馨浪漫'],
          label: '您期待的快乐气氛是:',
          valid: true
        }, {
          id: '4',
          required: true,
          selected: '',
          dataList: ['家庭', '饭店', '公司', '其他'],
          label: '您安排熊猫出现的场景是:',
          other: '',
          otherPlacholder: '请输入场景',
          valid: true
        }],
        formData: {
          address: '',
          phoneNumber: '',
          date: '',
          time: ''
        },
        formValid: {
          phoneNumberValid: true,
          dateValid: true,
        }
      };
    },
    methods: {
      onChange(e, item) {
        item.selected = e.target.value
        item.valid = true
      },
      submitInfo() {
        this.resetValid()
        for (let i = 0; i < this.formItems.length; i++) {
          const item = this.formItems[i]
          if (item.required && item.selected === '') {
            uni.showToast({
              title: item.label,
              icon: 'none',
              duration: 3000
            });
            item.valid = false
            return
          }
        }
        
        if (this.pagetype == '1') {
          if (!this.formData.phoneNumber) {
            uni.showToast({
              title: '请填写下单人手机号码',
              icon: 'none',
              duration: 3000
            });
            this.formValid.phoneNumberValid = false
            return
          }
          if (!this.formData.date || !this.formData.time) {
            uni.showToast({
              title: '请选择配送时间',
              icon: 'none',
              duration: 3000
            });
            this.formValid.dateValid = false
            return
          }
        }

        const params = this.getParams()

        uni.showLoading({
          title: '提交中'
        });
        feedbackSave(params).then(res => {
          if (res.data.code == 200) {
            uni.showToast({
              title: '提交成功！',
              icon: 'success',
              duration: 3000
            });
          } else {
            uni.showToast({
              title: '提交失败请刷新页面，重新提交',
              icon: 'error',
              duration: 2000
            });
          }
        }).catch(error => {
          uni.showToast({
            title: '提交失败请刷新页面，重新提交',
            icon: 'error',
            duration: 2000
          });
        }).finally(() => {
          uni.hideLoading()
        })
      },
      getParams() {
        const params = {
          address: this.formData.address,
          phoneNumber: this.formData.phoneNumber || undefined,
          openId: this.openId || sessionStorage.getItem("openId"),
          nickName: this.nickName || sessionStorage.getItem("nickName"),
          unionId: this.unionId ? this.unionId : sessionStorage.getItem("unionid"),
          questionGroup: this.formItems.map(item => {
            const selectedValue = item.dataList[item.selected]
            return {
              questionId: item.id,
              question: item.label,
              answer: selectedValue === '其他' ? item.other : selectedValue,
            }
          })
        }
        if (this.formData.date && this.formData.time) {
          const times = this.formData.time.split(' - ')
          params.deliveryStartTime = this.formData.date + ' ' + times[0] + ':00'
          params.deliveryEndTime = this.formData.date + ' ' + times[1] + (times[1].includes('59') ? ':59' : ':00')
        }
        return params
      },
      resetValid() {
        this.formItems.forEach(item => {
          item.valid = true
        })
        this.formValid.phoneNumberValid = true
        this.formValid.dateValid = true
      },
      getLocation() {
        return new Promise(resolve => {
          uni.getLocation({
            type: 'gcj02',
            success: (res) => {
              resolve(res)
            }
          })
        })
      },
      getMapAredss(latitude, longitude) {
        this.qqMap.reverseGeocoder({
          location: {
            latitude: latitude,
            longitude: longitude
          },
         	success: (res) => {
            if (res.message == 'query ok') {
              let a = res.result.address_component
           			this.address = res.result.address
              this.city = a.province + a.city + a.district
              this.formData.address = this.city
            }
          }
        })
      },
      showTimeSelect() {
        this.$refs.timeSelectorRef.show()
      },
      onDateConfirm(data) {
        this.formData.date = data.date
        this.formData.time = data.time
      }
    },
    onLoad() {
      this.getLocation().then(res => {
        this.getMapAredss(res.latitude, res.longitude)
      })
      wechatAuth().then(res => {
        if (res) {
          this.openId = res.openId
          this.nickName = res.nickName
          this.unionid = res.unionid
          this.uuid = res.uuid
        }
      }).catch((error) => {
        if (error === 'CODE_ERROR_1001' || error === 'CODE_ERROR_1003') {
          uni.showModal({
            title: '提示',
            content: '请刷新页面重试, ' + error,
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                console.log('用户点击确定');
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          });
        }
      })
    },
    components: {
      timeSelector
    }
  }
</script>

<style lang="scss" scoped>
  .content {
    margin-top: -10px;
    padding-top: 5px;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    padding-left: 10px;
    padding-right: 10px;
    background: #efefef;
  }

  .bg-bar {
    background-color: #d51717;
    height: 10px;
  }

  .demos-title {
    background-color: #d51717;
    text-align: center;
    font-size: 34px;
    color: #3cc51f;
    font-weight: 400;
    background-size: 100% 100%;
  }

  footer {
    text-align: center;
    font-size: 14px;
    padding: 20px;
  }

  footer a {
    color: #999;
    text-decoration: none;
  }

  .logo {
    height: 88px;
    overflow: hidden;
  }

  .logo .img {
    width: 250px;
    margin: 0 auto;
    margin-top: 25px;
  }


  ::v-deep .u-form-item {
    padding: 0 25px;
    position: relative;
    font-size: 15px;

    .u-form-item__body__left__content__label {
      font-size: 16px;
    }

    .form-item {
      color: rgb(192, 196, 204);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .picker {
      width: 100%;
    }
  }

  .title-bar {
    display: flex;
    padding: 6px 10px;
    align-items: center;
  }

  .title-bar .title {
    color: #d51717;
    margin-left: 10px;
  }

  .title-bar .tip {
    padding: 4px 5px;
    font-size: 12px;
    color: #ffffff;
    margin-left: 10px;
    background: #d51717;
    border-radius: 5px;
    line-height: 18x;
  }

  .bottom {
    padding: 0px 20px 50px 20px;
    margin-top: 23px;
  }

  /*改写边框及横线*/
  .weui-cells {
    border-radius: 10px;
    font-size: 19px;
  }

  .weui-cells:after,
  .weui-cells:before {
    position: fixed;
  }

  .input-disabled {
    color: #7F7F7F;
  }

  ::v-deep .u-form-item__body__right {
    padding-left: 20px
  }

  .error-status {
    border: 1px solid #d51717;
  }
</style>
